/**
 * 56. 合并区间
 * https://leetcode-cn.com/problems/merge-intervals/
 */
const { displayNestedArray } = require('../../libs/public');

/**
 * @param {number[][]} intervals
 * @return {number[][]}
 */
function merge(intervals) {
  intervals.sort((a, b) => a[0] - b[0]);
  const result = [intervals[0]];
  let node = result[0];
  const { length } = intervals;
  for (let i = 1; i < length; i += 1) {
    const item = intervals[i];
    const [iLeft, iRight] = item;
    const [nLeft, nRight] = node;
    if (nLeft > iRight || nRight < iLeft) {
      result.push(item);
      node = item;
    } else {
      node[0] = Math.min(nLeft, iLeft);
      node[1] = Math.max(nRight, iRight);
    }
  }
  return result;
}

console.log(displayNestedArray(merge([[2, 6], [1, 3], [8, 10], [15, 18]])) === '[[1,6],[8,10],[15,18]]');
console.log(displayNestedArray(merge([[1, 4], [4, 5]])) === '[[1,5]]');
console.log(displayNestedArray(merge([[1, 4], [5, 6]])) === '[[1,4],[5,6]]');
console.log(displayNestedArray(merge([[1, 4], [0, 0]])) === '[[0,0],[1,4]]');
console.log(displayNestedArray(merge([[1, 4], [0, 5]])) === '[[0,5]]');
